import { getToken, setToken, removeToken } from '@/utils/auth'
import {getInfo, login, logout} from "@/api/login";

interface userInfo {
    username: string;
    password: string;
    verificationCode?:string
}
const user = defineStore('user', {
    state: ()  => ({
        token: getToken(),
        id:'',
        name: '',
        avatar: '',
        userInfo:'',
        roles: [],
        permissions: [],
    }),
    actions: {
        // 登录
        async Login(user: userInfo) {
            const res = await login(user);
            this.token =  res.token;
            setToken(res.token)
        },
        // 获取用户信息
        async GetInfo() {
            const res = await getInfo();
            // console.log(res)
            const user = res.user

            const avatar = user.avatar ||  "http://image.xlfdeblog.top/blog/6f01ea57bbcb910fd452f684f4305019.jpg";

            if (res.roles && res.roles.length > 0) { // 验证返回的roles是否是一个非空数组
                this.roles = res.roles;
                this.permissions = res.permissions;
            } else {
                this.roles = ['ROLE_DEFAULT']
            }
            this.userInfo = user
            this.id = user.userId
            this.name = user.userName
            this.avatar = avatar
     }, // 退出系统
     async LogOut() {
         removeToken()
         this.$reset();
         await logout()
     },
    },
    getters: {
        isLogin : (state) => { return state.token != null }
    },
})

export default user
